package com.example.xlmkotlinwanandroid.network

import androidx.paging.PositionalDataSource
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

//文章数据源

class ArticleDataSource :
    PositionalDataSource<ArticleResponse2.ArticleBean2>() {

    var startPosition = 0

    //初始化加载第一页的数据
    override fun loadInitial(
        params: LoadInitialParams,
        callback: LoadInitialCallback<ArticleResponse2.ArticleBean2>
    ) {
        Network.apiService.getArticleList2(startPosition).enqueue(object : Callback<ArticleResponse2> {
            override fun onResponse(call: Call<ArticleResponse2>, response: Response<ArticleResponse2>) {
                val body = response.body()
                val total = body?.data?.total
                val datas = body?.data?.datas

                if (datas != null) {
                    callback.onResult(datas, 0,total!!)
                }
            }

            override fun onFailure(call: Call<ArticleResponse2>, t: Throwable) {

            }
        })
    }

    override fun loadRange(
        params: LoadRangeParams,
        callback: LoadRangeCallback<ArticleResponse2.ArticleBean2>
    ) {
        Network.apiService.getArticleList2(params.startPosition)
            .enqueue(object : Callback<ArticleResponse2> {
                override fun onResponse(
                    call: Call<ArticleResponse2>,
                    response: Response<ArticleResponse2>
                ) {
                    val body = response.body()
                    val datas = body?.data?.datas
                    if (datas != null) {
                        callback.onResult(datas)
                    }

                }

                override fun onFailure(call: Call<ArticleResponse2>, t: Throwable) {

                }
            })
    }


}